<template>
  <div class="app-container">

    <div class="filter-container">
      <el-form>
        <el-form-item>
          <p style="float: left; font-family: Helvetica; font-size: 28px; margin: 8px auto;padding-left: 4px;">文件列表</p>
          <el-button type="primary" style="float: left;margin: 12px 8px;" size="small" icon="plus"
                     @click="uploadFileButton">
            上传文件
          </el-button>

          <el-button type="primary" style="float: left;margin: 12px 8px;" size="small" icon="plus"
                     @click="convertTaskButton">
            创建城市管理检测任务
          </el-button>
          <div style="float: right;  margin: 8px auto;padding-left: 4px;">
            <el-input clearable v-model="searchText" prefix-icon="el-icon-search" v-on:clear="searchEvent" onkeypress='if(window.event.keyCode==13) this.blur()' v-on:blur="searchEvent"  size="small" style="width:200px; height: 40px; margin-top: 8px;" placeholder="请输入内容"/>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div>
<!--  获取文件列表    -->
      <el-table  :data="fileList" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit @selection-change="handleSelectionChange" :row-key="getRowKeys"
                highlight-current-row>

        <el-table-column  align="center" :reserve-selection="true" @selection-change=""
                          type="selection"
                          width="40" label="文件选择">
        </el-table-column>

        <el-table-column align="center" label="序号" width="80">
          <template slot-scope="scope">
            <span v-text="getIndex(scope.$index)"> </span>
          </template>
        </el-table-column>
        <el-table-column v-if="false" align="center" label="ID" prop="id" style="width: 40px;"></el-table-column>
        <el-table-column align="center" label="文件名称" prop="fileName" style="width: 40px;"></el-table-column>

        <el-table-column align="center" label="文件类型" style="width: 40px;">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.fileType==='1' || scope.row.fileType===1 || scope.row.fileType==='video'"  effect="plain" type="success">{{
                fileType.off_video
              }}</el-tag>
            <el-tag v-if="scope.row.fileType==='2' || scope.row.fileType===2 || scope.row.fileType==='image'"  effect="plain" type="primary">{{
                fileType.image
              }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建时间" style="width: 40px;">
          <template slot-scope="scope">
            <span v-text="dateToString(scope.row.createTime)"></span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="更新时间" style="width: 40px;">
          <template slot-scope="scope">
            <span v-text="dateToString(scope.row.updateTime)"></span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" style="width: 40px;">
          <template slot-scope="scope">
            <el-button size="small" style="padding: 4px 8px;" @click="showResource(scope.row)">浏览</el-button>
            <a :href="getDownloadHref(scope.row.fileName)" :download="scope.row.fileName">
              <el-button size="small" style="padding: 4px 8px;">下载</el-button>
            </a>
            <el-button size="small" style="padding: 4px 8px; " @click="deleteResource(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

<!--  分页条  -->
    <div v-if="paginationVisible">
      <div style="width: 100%;height: auto;margin-top: 10px;">
        <div class="block" style="width: 45%;height: auto; margin: 0 0;">
          <el-pagination
            @size-change="handleSizeChange($event)"
            @current-change="handleCurrentChange($event)"
            :current-page="listQuery.pageNum"
            :page-sizes="listQuery.sizeList"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listQuery.totalCount">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 上传文件对话框   -->
    <el-dialog width="50%" :title="pageParams.upLoadFileTitle" :visible.sync="pageParams.uploadFileDialogFormVisible">
      <el-tabs v-model="tabName" type="card" style="padding: 0;">
        <el-tab-pane v-if="true" label="文件上传" name="mix">
          <!-- action必选参数, 上传的地址 -->
          <el-upload
            class="upload-demo"
            ref="uploadMix"
            :limit="5"
            action="/uploadfile/upload"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-change="handleUploadChange"
            name="file"
            accept="image/*,video/*"
            :auto-upload="false"
            multiple
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          </el-upload>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" v-on:click="fileSubmit">上传</el-button>
        <el-button size="small" v-on:click="clearFiles">清空文件</el-button>
        <el-button size="small" @click="pageParams.uploadFileDialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>


    <!--创建转换任务对话框-->
    <!--  向服务器提交的数据保存在taskRequestData中，通过this.api()提交  -->
    <el-dialog :title="pageParams.createTaskDialogTitle" :visible.sync="pageParams.createTaskDialogFormVisible"
               width="50%">
      <el-form ref="taskRequestData" :model="taskRequestData" :rules="taskRequestDataRules" autoComplete="on"  v-loading.body="pageParams.createTaskDialogLoading"
               label-width="80px"  label-position="left">

        <el-form-item label="任务名称" style="width: 95%" prop="taskName">
          <el-input v-model="taskRequestData.taskName" autoComplete="on" v-on:blur="isNumberAndLetter(taskRequestData.taskName)" placeholder="输入名称"></el-input>
        </el-form-item>

        <!-- 1:检测道路， 2: 检测摊贩, 3:检测自行车, 4:检测遗留物, 5:检测人员聚集 6:视频摘要 -->
        <el-form-item label="算法类型" style="width: 95%" prop="algorithmType" required>
          <el-select v-model="taskRequestData.algorithmType" autoComplete="on" placeholder="请选择算法类型">
            <el-option :label="algorithmTypeList.detectFireExits" value="1"></el-option>
            <el-option :label="algorithmTypeList.detectFirePerson" value="2"></el-option>
            <el-option :label="algorithmTypeList.detectFireDehazing" value="3"></el-option>
            <el-option :label="algorithmTypeList.detectFire" value="4"></el-option>
            <el-option :label="algorithmTypeList.detectFireDoor" value="5"></el-option>
          </el-select>
          <!--          <el-input v-model="taskRequestData.algorithmType" placeholder="输入算法类型"></el-input>-->
        </el-form-item>

        <el-form-item label="任务类型" prop="taskType" required>
          <el-select v-model="taskRequestData.taskType" autoComplete="on" placeholder="请选择任务类型">
            <el-option :label="taskTypeName.off_video" value="1"></el-option>
            <el-option :label="taskTypeName.image" value="2"></el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="缓存个数" style="width: 34.3%" prop="cacheNumber" v-if="(taskRequestData.algorithmType === 5 || taskRequestData.algorithmType === '5')">-->
<!--          <el-input v-model="taskRequestData.cacheNumber" autoComplete="on"  v-on:blur="isNumber(taskRequestData.cacheNumber)" placeholder="输入单车检测缓存数,默认缓存10个"></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="文件名称" prop="taskFileNames" required>
          <span v-for="taskFile in taskRequestData.taskFiles" autoComplete="on">
            <div onMouseOver="this.style.color='red'" onMouseOut="this.style.color='#000000'"  style="overflow-x:auto; white-space:nowrap;  float: left;margin-right: 6px; width: 30%; cursor: pointer;" v-on:click="taskFileShow(taskRequestData.taskFiles, taskFile.fileId, taskFile.fileName)">
              {{ taskFile.fileName }}
            </div>
          </span>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="createConvertTask">立即创建</el-button>
        <el-button size="small" @click="clearSelectedFiles">清空所选文件</el-button>
        <el-button size="small" @click="pageParams.createTaskDialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>


    <el-dialog id="imageAndVideoDialog" :title="showSwitch.title" :visible.sync="dialogVisible" width="50%" v-on:close="closeDialog">
      <div v-if="showSwitch.show" style="width: 100%; height: auto;">
        <div v-if="showSwitch.isDrawPolygon" ref="collapseDiv1" style="position: relative; width: 100%;" class="collapseDiv image">
          <div style="position: absolute; float: left; width: 100%;" ref="collapseDiv2" class="collapseDiv">
            <img class="imageAndVideo" style="width: 100%; height: auto;" :src="dialogImageUrl" alt="" ref="drawPolygonImage" id="drawPolygonImage">
          </div>
          <canvas ref="image"  style="position: absolute; float: left;" id="imageCanvas" class="testDiv"></canvas>
        </div>
        <div v-else  style="width: 100%; height: auto;">
          <img :src="dialogImageUrl" style="width: 100%; height: auto;"/>
        </div>
      </div>

      <div v-else style="width: 100%; height: auto;"  >
        <div v-if="showSwitch.isDrawPolygon" style="position: relative; width: 100%;" ref="collapseDiv3" class="collapseDiv video">
          <div class="collapseDiv" ref="collapseDiv4" style="position: absolute; float: left; width: 100%;">
            <video class="imageAndVideo"  ref="videoPlayer" :autoplay="true" style="width: 100%;height: auto;" v-model="dialogVideoUrl" :src="dialogVideoUrl" rel="drawPolygonVideo" id="drawPolygonVideo"  controls>
              <source :src="dialogVideoUrl" style="width:100%; height: auto;" >
            </video>
          </div>
          <canvas ref="video"  style="position: absolute; float: left;" id="videoCanvas" class="testDiv"></canvas>
        </div>
        <div v-else style="width: 100%; height: auto;">
          <video ref="videoPlayer" v-model="dialogVideoUrl" width="100%" height="auto" :src="dialogVideoUrl"  controls>
            <source :src="dialogVideoUrl" style="width:100%; height:auto">
          </video>
        </div>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" v-if="showSwitch.isCreateTask && (taskRequestData.algorithmType === 5 || taskRequestData.algorithmType === '5' || taskRequestData.algorithmType === 1 || taskRequestData.algorithmType === '1')" @click="drawPolygonEvent(showSwitch.selectingFileName,true)">绘制待检测区域</el-button>
        <el-button size="small" type="primary" v-if="showSwitch.isCreateTask && (taskRequestData.algorithmType === 5 || taskRequestData.algorithmType === '5' || taskRequestData.algorithmType === 1 || taskRequestData.algorithmType === '1')" @click="drawPolygonEvent(showSwitch.selectingFileName, false)">绘制非检测区域</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import $ from "jquery"
import elementResizeDetectorMaker from "element-resize-detector";
//引入video样式
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'
import {videoPlayer} from "vue-video-player/src";
//引入hls.js
// import 'videojs-contrib-hls/src/videojs-contrib-hls'
// import 'videojs-contrib-hls/src/videojs.js'

import {parseTime} from '../../utils';
// import x from "./image"
//新建一个请求
import axios from "axios";
import {Message} from "element-ui";
import store from "../../store";
import service from "../../utils/api";

const api = axios.create({
  baseURL: process.env.BASE_URL, // api的base_url
  timeout: 15000                  // 请求超时时间2
})

export default {
  name: "file",
  inject:['reload'],
  data() {
    return {
      searchText:"",
      isSearch:false,
      isPreSearch:false,

      dialogStyle:{
        width:0,
        height:0
      },
      getRowKeys(fileList){
        return fileList.id
      },

      ////////////////////////////////////////
      //上传文件的视频与图片url
      ////////////////////////////////////////
      image:"",
      video: "",

      /////////////////////////////////////////
      //图片上传(image)未使用、视频上传(video)未使用、混合上传(mix)使用
      ////////////////////////////////////////
      tabName:"mix",

      /////////////////////////////////////////
      //上传文件时，控制图片与视频的预览，同上（未使用）
      //////////////////////////////////////////
      dialogImageUrl: '',
      dialogVideoUrl: '',


      //////////////////////////////////////////
      //文件上传时，要附加的数据(还未使用)
      /////////////////////////////////////////
      uploadAttachData: {},

      /////////////////////////////////////////////
      //创建任务请求上传参数
      /////////////////////////////////////////////
      taskRequestData: {
        algorithmType: '',//非必须String
        taskName: '',//非必须String
        taskType: '',//1:离线视频 2:图片String
        taskFiles: [],//String
        coordPoints: [],
        skipCoordPoints:[],
        cacheNumber: 10
      },

      /////////////////////////////////////////////
      //创建任务请求上传参数验证
      //////////////////////////////////////////////
      taskRequestDataRules: {
        taskName:[{required: true, trigger: 'blur', message: "请输入任务名称，限字母或数字"}],
        algorithmType: [{required: true, trigger: 'blur', message: "请选择算法类型"}],
        taskType: [{required: true, trigger: 'blur', message: "请选择任务类型"}],
        taskFiles: [{required: true, trigger: 'blur', message: "请选择文件"}],
        cacheNumber:[{required: true, trigger: 'blur', message: "请输入单车检测缓存个数，仅限数字"}]
      },

      /////////////////////////////////////////////////
      //页面设置
      //当前页面所用的参数，比如标题，控制对话框的显示
      /////////////////////////////////////////////////
      pageParams: {
        uploadFileDialogFormVisible: false,
        createTaskDialogFormVisible: false,
        createTaskDialogLoading: false,
        upLoadFileTitle: "文件上传",
        createTaskDialogTitle: "创建城市管理检测任务",
        showProgress: false,
        convertTaskButtonVisible: false,
        isCheck: false
      },
      //页面加载动画控制
      listLoading: true,


      //////////////////////////////////////////////////////
      //文件类型
      ///////////////////////////////////////////////////////
      fileType: {
        off_video: "离线视频",
        image: "图片"
      },

      //////////////////////////////////////////////////////
      //从后台获取的文件列表
      //////////////////////////////////////////////////////
      fileList: [],
      paginationVisible:true,


      ///////////////////////////////////////////////
      //分页查询设置，url
      ///////////////////////////////////////////////
      listQuery: {
        url: "/uploadfile/list",
        pageRow: 10,//页大小
        pageNum: 1,//当前页
        totalPage: 0,//总页数
        totalCount: 0,//总数据大小
        sizeList: [10, 20, 50, 100]
      },
      listSearchQuery: {
        url: "/uploadfile/query"
      },

      listQueryTemp: {
        url: "/uploadfile/list",
        pageRow: 10,//页大小
        pageNum: 1,//当前页
        totalPage: 0,//总页数
        totalCount: 0,//总数据大小
        sizeList: [10, 20, 50, 100]
      },


      ///////////////////////////////////////////
      //任务类型
      //保存任务类型名称，便于显示
      ///////////////////////////////////////////
      taskTypeName: {
        image: '图片',
        off_video: '离线视频',
        on_video: '实时视频'
      },


      ///////////////////////////////////////////////////////////////////////////////
      //<!--任务状态  1.创建 2.成功 3.失败 4.取消-->
      //1:任务创建, 2:转换成功, 3:转换部分成功, 4:转换失败, 5:取消转换,  8:下发失败, 9:下发成功
      //保存任务状态名称便于显示
      ///////////////////////////////////////////////////////////////////////////////
      taskStatusName: {
        create: '任务创建',
        success: "检测成功",
        partialSuccess: "部分检测成功",
        fail: '检测失败',
        cancel: '取消检测',
        giveTaskError: "下发失败",
        giveTaskSuccess: "下发成功"
      },


      /////////////////////////////////////////
      //算法类型信息
      // 1、消防通道检测: detectFireExits
      // 2、被困人员检测: detectFirePerson
      // 3、火场图像去雾: detectFireDehazing
      // 4、火灾智能检测: detectFire
      // 5、防火门检测: detectFireDoor
      /////////////////////////////////////////
      algorithmTypeList: {
        detectFireExits: "消防通道检测",
        detectFirePerson:"被困人员检测",
        detectFireDehazing:"火场图像去雾",
        detectFire:"火灾智能检测",
        detectFireDoor:"防火门检测"
      },


      /////////////////////////////////
      //文件下载URL
      /////////////////////////////////
      fileDownloadUrl:"/repository",

      ////////////////////////////////////////////////////////
      //图片视频浏览窗口
      ////////////////////////////////////////////////////////
      //show开关，控制是否显示图片或则视频:true为图片， false为视频
      dialogVisible: false,
      showSwitch: {
        url: "/repository",
        title: "图片/视频",
        show: true,
        isCreateTask: false,
        isDrawPolygon: false,
        selectingFileName:""
      },

      //////////////////////////////////////////////
      //绘制多边形
      //记录多边形点{fileId:"123", point:[[x1,y1],[x2,y2]]}
      //////////////////////////////////////////////
      polygonPoint:[],
      polygonNoCheckPoint: [],
      //记录当前要绘制多边形的文件Id,等同于在创建任务中正在查看的文件，由于查看文件与绘制多边形在两个分离的过程中，所以通过中间量进行记录绘制文件
      polygonId:0,


      observer: null,

      listen: 10
    }
  },
  mounted () {
  },
  beforeDestroyed () {
    if (this.observer) {
      this.observer.disconnect()
      this.observer.takeRecords()
      this.observer = null
    }
  },
  watch: {
    dialogVisible: {
      handler(newName, oldName) {
        if (newName === false) {
          document.onmousedown = null
          let canvas = document.getElementById('imageCanvas')
          if (undefined !== canvas && canvas != null) {
            canvas.style.opacity = '0.7'
          }
        }
      },
      immediate: false
    },
    polygonPoint: {
      handler(newName, oldName) {
        let index = 0
        for (index; index < this.polygonPoint.length; index++) {
          if (this.polygonPoint[index].fileId === this.polygonId) {
            break
          }
        }
        if (this.showSwitch.show) {
          this.drawImageAndPoints("imageCanvas", "drawPolygonImage", this.polygonPoint[index].point, this.polygonNoCheckPoint[index].point)
        } else {
          this.drawImageAndPoints("videoCanvas", 'drawPolygonVideo', this.polygonPoint[index].point, this.polygonNoCheckPoint[index].point)
        }
      },
      deep: true,
      immediate: false
    },

    polygonNoCheckPoint: {
      handler(newName, oldName) {
        let index = 0
        for (index; index < this.polygonNoCheckPoint.length; index++) {
          if (this.polygonNoCheckPoint[index].fileId === this.polygonId) {
            break
          }
        }
        if (this.showSwitch.show) {
          this.drawImageAndPoints("imageCanvas", "drawPolygonImage", this.polygonPoint[index].point, this.polygonNoCheckPoint[index].point)
        } else {
          this.drawImageAndPoints("videoCanvas", 'drawPolygonVideo', this.polygonPoint[index].point, this.polygonNoCheckPoint[index].point)
        }
      },
      deep: true,
      immediate: false
    },
  },

  created() {
    this.pageParams.uploadFileDialogFormVisible = false;
    //在该方法中，向后台获取文件列表的数据，放到fileList中
    this.getFileList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow, this.isSearch)
  },

  methods: {

    searchEvent(){
      if(this.searchText !== ""){
        // this.$message.error("该功能暂不支持")
        // this.isSearch = true
        // this.listQuery = this.listSearchQuery
        this.conditionQuery(this.listSearchQuery.url, this.searchText)
        this.paginationVisible = false
      }else{
        // this.$message.error("空搜索")
        // this.isSearch = false
        // this.listQuery = this.listQueryTemp
        this.getFileList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow,this.isSearch)
        this.paginationVisible = true
      }
    },
    //Date转string类型，显示时间
    dateToString(date) {
      return parseTime(date)
    },
    isNumber(value){
      if(!this.regNumber(value)){
        this.$message.error("单车检测缓存个数,不符合数字规范")
      }
    },
    regNumber(value){
      let reg = /^[0-9]+$/
      if(!reg.test(value)){
        return false
      }
      return true
    },
    //判断是否为字母数字
    reg(value){
      let reg = /^[0-9a-zA-Z]+$/
      if(!reg.test(value)){
        return false
      }
      return true
    },

    //判断是否是，字母数字
    isNumberAndLetter(value){
      if(!this.reg(value)){
        this.$message.error("任务名不符合数字或字母规范")
      }
    },

    //构建文件下载链接
    getDownloadHref(fileName) {
      return this.fileDownloadUrl + fileName;
    },

    //获得文件列表序号
    getIndex($index) {
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },

    //处理文件上传改变
    handleUploadChange(file, fileList){
      if(this.tabName === "image"){
        this.dialogVideoUrl = file.url;
        this.video = file.url
      }else if(this.tabName === "video"){
        this.dialogImageUrl = file.url;
        this.image = file.url
      }else {
        // this.$refs.uploadMix.fileList = fileList.slice(-1);
      }
    },

    //处理文件上传预览
    handleUploadPreview(file){
      if(this.tabName === "image"){
        this.dialogImageUrl = file.url;
      }else if(this.tabName === "video"){
        this.dialogVideoUrl = file.url;
        this.video = file.url
      }else {

      }
    },

    //文件上传submit
    fileSubmit(){
      if(this.tabName === "image"){
        this.$refs.uploadImage.submit();
      }else if(this.tabName === "video"){
        this.$refs.uploadVideo.submit();
      }else {
        this.$refs.uploadMix.submit();
      }
    },

    //清空上传的文件
    clearFiles() {
      if(this.tabName === "image"){
        this.image = ""
        this.$refs.uploadImage.clearFiles();
      }else if(this.tabName === "video"){
        this.video = ""
        this.$refs.uploadVideo.clearFiles();
      }else {
        this.$refs.uploadMix.clearFiles();
      }
    },

    handleRemove(file) {
      if(this.tabName === "image"){
        this.$refs.uploadImage.abort(); //取消上传
      }else if(this.tabName === "video"){
        this.$refs.uploadVideo.abort(); //取消上传
      }else {
        this.$refs.uploadMix.abort(); //取消上传
      }
    },

    handleSuccess(res){
      this.pageParams.uploadFileDialogFormVisible = false;
      if(this.tabName === "image"){
        this.$refs.uploadImage.abort(); //取消上传
      }else if(this.tabName === "video"){
        this.$refs.uploadVideo.abort(); //取消上传
      }else {
        this.$refs.uploadMix.abort(); //取消上传
      }
      if(res.code===100){
        this.$message.success(res.msg);
      }else{
        this.$message.error(res.msg);
      }
      if(this.listQuery.pageNum === 1){
        this.getFileList(this.listQuery.url, 1, this.listQuery.pageRow, this.isSearch)
      }
    },

    handleError() {
      if(this.tabName === "image"){
        this.$refs.uploadImage.abort(); //取消上传
      }else if(this.tabName === "video"){
        this.$refs.uploadVideo.abort(); //取消上传
      }else {
        this.$refs.uploadMix.abort(); //取消上传
      }
      this.$message.error("上传文件失败")
    },

    closeDialog(){
      this.dialogVisible = false
      let _this = this
      setTimeout(function () {
        _this.dialogImageUrl = ""
        _this.showSwitch.title = "图片/视频"
        _this.showSwitch.show = true
        _this.showSwitch.isCreateTask = false
        _this.showSwitch.isDrawPolygon = false
      }, 100)
    },
    //控制四个按钮：文件上传，创建转换任务，下载删除
    uploadFileButton() {
      this.pageParams.uploadFileDialogFormVisible = true
    },
    convertTaskButton() {
      if (this.taskRequestData.taskFiles.length > 0) {
        this.pageParams.createTaskDialogFormVisible = true;
      } else {
        this.pageParams.createTaskDialogFormVisible = false;
        this.$message.error("请先勾选文件");
      }
    },
    ////////////////////////////////////////
    //删除文件提示
    ////////////////////////////////////////
    deleteResource(row) {
      this.$confirm('将删除该文件, 是否确定', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = row.id
        let data = {id: id}
        api({
          url: "/uploadfile/delete",
          method: "post",
          data: data
        }).then(data => {
          data = data.data
          if (data.code === '100' || data.code === 100) {
            if(this.searchText === ""){
              this.getFileList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow, this.isSearch)
              this.paginationVisible = true
            }else {
              this.conditionQuery(this.listSearchQuery.url, this.searchText)
            }
            this.$message.success(data.msg)
          }
        }).catch(data => {
          this.$message.error("删除文件失败")
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },



    //////////////////////////////
    //listToDict
    listToDict(list){
      let newList = []
      for(let i = 0; i < list.length; i++){
        let xy =  list[i]
        let x = xy[0]
        let y = xy[1]
        let dict = {x: x, y:y}
        newList.push(dict)
      }
      return newList
    },

    dictToList(dict){
      let newDict = []
      for(let i = 0; i < dict.length; i++){
        let xy = dict[i]
        let x = xy.x
        let y = xy.y
        let list = [x, y]
        newDict.push(list)
      }
      return newDict
    },

    /////////////////////////////
    //创建转换任务
    //////////////////////////////
    createConvertTask() {
      //////////////////////////////
      //检查参数
      let taskLabel = this.reg(this.taskRequestData.taskName)
      if(!taskLabel){
        let _this=this
        setTimeout(function () {
          _this.$message.error("任务名不符合数字或字母规范")
        }, 1)
      }

      let algorithmTypeLabel = (this.taskRequestData.algorithmType !== "")
      if(!algorithmTypeLabel){
        let _this=this
        setTimeout(function () {
          _this.$message.error("算法类型不可为空")
        }, 1)
      }

      let taskTypeLabel = (this.taskRequestData.taskType !== "")
      if(!taskTypeLabel){
        let _this=this
        setTimeout(function () {
          _this.$message.error("任务类型不可为空")
        }, 1)
      }

      let taskFilesLabel = (this.taskRequestData.taskFiles.length > 0)
      if(!taskFilesLabel){
        let _this=this
        setTimeout(function () {
          _this.$message.error("检测任务文件不可为空")
        }, 1)
      }

      if (!taskLabel || !algorithmTypeLabel || !taskTypeLabel || !taskFilesLabel){
        return
      }

      //一个任务创建一个多边形

      if(this.taskRequestData.algorithmType === 1 || this.taskRequestData.algorithmType === '1' || this.taskRequestData.algorithmType === 5 || this.taskRequestData.algorithmType === '5'){
        if(this.polygonPoint.length !== 0 && this.polygonPoint[0].point.length !== 0){
          this.taskRequestData.coordPoints = this.listToDict(this.polygonPoint[0].point)
        }else {
          this.taskRequestData.coordPoints = []
        }
        if(this.polygonNoCheckPoint.length !== 0 && this.polygonNoCheckPoint[0].point.length !== 0){
          //0表示一个任务绘制一个框
          this.taskRequestData.skipCoordPoints = this.listToDict(this.polygonNoCheckPoint[0].point)
        }else {
          this.taskRequestData.skipCoordPoints = []
        }
      }else {
        this.taskRequestData.coordPoints = []
        this.taskRequestData.skipCoordPoints = []
      }
      console.log(self.taskRequestData)
      api({
        url: '/converttask/new',
        method: "post",
        data: this.taskRequestData
      }).then(data => {
        data = data.data
        if (data.code === '100' || data.code === 100) {
          this.$message.success(data.msg)
          this.pageParams.createTaskDialogFormVisible = false
        } else {
          this.$message.error(data.msg)
        }
      }).catch(data => {
        this.$message.error("创建检测任务失败")
      })
    },


    //清空转换任务的所选文件ID
    clearSelectedFiles() {
      this.taskRequestData.taskFiles = [];
      this.reload();
    },

    //点击图片播放视频
    playVideo(){
      this.dialogVideoUrl = this.video
    },
    playImage(){
      this.dialogImageUrl = this.image
    },

    //获得鼠标点击
    onmouseDown(ev) {
      let mousePos = this.mouseCoords(ev);
      //鼠标点击的点
      let mousePosX = mousePos.x
      let mousePosY = mousePos.y
      this.$nextTick(()=> {
        let image = null
        let imageDialog = null
        if(this.showSwitch.show){
          image = document.getElementsByClassName("image")[0]
        }else{
          image = document.getElementsByClassName("video")[0]
        }
        imageDialog = document.getElementById("imageAndVideoDialog")

        let width = image.clientWidth
        let height = image.clientHeight
        let x_off = image.offsetLeft
        let y_off = image.offsetTop
        let offsetParent = image.offsetParent
        let offsetParentx_off = offsetParent.offsetLeft
        let offsetParenty_off = offsetParent.offsetTop


        let scrollTop = imageDialog.scrollTop
        let scrollLeft = imageDialog.scrollLeft
        //左上的坐标点
        let pos_x1 = offsetParentx_off + x_off - scrollLeft
        let pos_y1 = offsetParenty_off + y_off - scrollTop
        //右下点坐标
        let pos_x2 = pos_x1 + width
        let pos_y2 = pos_y1 + height
        if(mousePosX>=pos_x1 && mousePosX <= pos_x2){
          if(mousePosY >= pos_y1 && mousePosY <= pos_y2){
            // console.log("==================================")
            // console.log("左上点："+pos_x1 + "-" + pos_y1)
            // console.log("图片宽高："+width + "-" + height)
            // console.log("右下点："+pos_x2 + "-" + pos_y2)
            // console.log("鼠标点击点："+mousePosX+"-"+mousePosY)
            // console.log("鼠标点击坐标："+(mousePosX - pos_x1)+"-"+(mousePosY - pos_y1))

            for(let i=0;i<this.polygonPoint.length;i++){
              if(this.polygonPoint[i].fileId === this.polygonId){
                let p =  [(mousePosX-pos_x1)/width, (mousePosY-pos_y1)/height]
                this.polygonPoint[i].point.push(p)
              }
            }
          }
        }
      })
    },


    //获得鼠标点击
    onmouseDownNoCheck(ev) {
      let mousePos = this.mouseCoords(ev);
      //鼠标点击的点
      let mousePosX = mousePos.x
      let mousePosY = mousePos.y
      this.$nextTick(()=> {
        let image = null
        let imageDialog = null
        if(this.showSwitch.show){
          image = document.getElementsByClassName("image")[0]
        }else{
          image = document.getElementsByClassName("video")[0]
        }
        imageDialog = document.getElementById("imageAndVideoDialog")

        let width = image.clientWidth
        let height = image.clientHeight
        let x_off = image.offsetLeft
        let y_off = image.offsetTop
        let offsetParent = image.offsetParent
        let offsetParentx_off = offsetParent.offsetLeft
        let offsetParenty_off = offsetParent.offsetTop


        let scrollTop = imageDialog.scrollTop
        let scrollLeft = imageDialog.scrollLeft
        //左上的坐标点
        let pos_x1 = offsetParentx_off + x_off - scrollLeft
        let pos_y1 = offsetParenty_off + y_off - scrollTop
        //右下点坐标
        let pos_x2 = pos_x1 + width
        let pos_y2 = pos_y1 + height
        if(mousePosX>=pos_x1 && mousePosX <= pos_x2){
          if(mousePosY >= pos_y1 && mousePosY <= pos_y2){
            // console.log("==================================")
            // console.log("左上点："+pos_x1 + "-" + pos_y1)
            // console.log("图片宽高："+width + "-" + height)
            // console.log("右下点："+pos_x2 + "-" + pos_y2)
            // console.log("鼠标点击点："+mousePosX+"-"+mousePosY)
            // console.log("鼠标点击坐标："+(mousePosX - pos_x1)+"-"+(mousePosY - pos_y1))

            for(let i=0;i<this.polygonNoCheckPoint.length;i++){
              if(this.polygonNoCheckPoint[i].fileId === this.polygonId){
                let p =  [(mousePosX-pos_x1)/width, (mousePosY-pos_y1)/height]
                this.polygonNoCheckPoint[i].point.push(p)
              }
            }
          }
        }
      })
    },

    mouseCoords(ev) {
      if(ev.pageX || ev.pageY){
        return {x:ev.pageX, y:ev.pageY};
      }
      return{
        x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y:ev.clientY + document.body.scrollTop - document.body.clientTop
      };
    },


    conditionQuery(url, fileName){
      api({
        url: url + '/?fileName=' + fileName,
        method: "get"
      }).then(data => {
        data = data.data
        if (data.code === '100' || data.code === 100) {
          this.fileList = data.info;
        } else {
          this.$message.error(data.msg)
        }
      }).catch(data => {
        this.$message.error('加载文件列表失败');
      })
    },

    //////////////////////////////////////////////////////
    //获得文件列表:url=/uploadfile/list/?pageNum=5&pageRow=4"
    ///////////////////////////////////////////////////////
    getFileList(url, pageNum, pageRow, isSearch=false, searchText="") {

      // if(this.isPreSearch === false && isSearch){
      //   this.listQueryTemp = this.listQuery
      //   this.isPreSearch = isSearch
      // }else if(this.isPreSearch ===true && !isSearch){
      //   this.listQuery = this.listQueryTemp
      //   this.isPreSearch = isSearch
      // }
      //
      // let requsestUrl = url + '/?pageNum=' + pageNum + '&pageRow=' + pageRow
      // if(isSearch && searchText !== ""){
      //   requsestUrl = requsestUrl + "&searchText=" + searchText
      // }

      api({
        url: url + '/?pageNum=' + pageNum + '&pageRow=' + pageRow,
        method: "get"
      }).then(data => {
        data = data.data
        if (data.code === '100' || data.code === 100) {
          this.fileList = data.list;
          this.listQuery.totalCount = data.totalCount
          this.listQuery.totalPage = data.totalPage
          this.listLoading = false;
        } else {
          this.$message.error(data.msg)
        }
      }).catch(data => {
        this.listLoading = false;
        this.$message.error('加载文件列表失败');
      })
    },


    handleSizeChange(val) {
      // 处理当前页大小变化
      this.listQuery.pageRow = val
      // 防止数据溢出，当页大小改变时，从第一页开始查
      this.listQuery.pageNum = 1
      this.getFileList(this.listQuery.url, 1, this.listQuery.pageRow, this.isSearch, this.searchText)
    },
    handleCurrentChange(val) {
      // 处理当前页号变化
      this.listQuery.pageNum = val
      //  截取显示数据
      this.getFileList(this.listQuery.url, this.listQuery.pageNum, this.listQuery.pageRow, this.isSearch, this.searchText)
    },

    isImage(fileName){
      let ext3 = fileName.substr(fileName.length - 3, 3)
      let ext4 = fileName.substr(fileName.length - 4, 4)
      let imageFlag = false;
      let errorType = false
      if (ext3 === 'jpg' || ext3 ==='png' || ext3 ==='gif' || ext3 ==='bmp' || ext3 === 'svg' ){
        imageFlag = true
      }else if(ext4 === 'jpeg'){
        imageFlag = true
      }else if(ext3 === 'mp4' || ext3 ==='avi' || ext3 ==='mov' || ext3 ==='wmv' || ext3 ==='asf' || ext3 ==='3gp' || ext3 ==='mkv' || ext3 ==='f4v') {
        imageFlag = false
      }else if(ext4 ===  'navi' || ext4 ==='rmvb' || ext4 ==='webm') {
        imageFlag = false
      }else {
        errorType = true
      }
      return [imageFlag, errorType]
    },

    //浏览
    showResource(row) {
      let fileName = row.fileName
      let imageFlag = this.isImage(fileName)[0]
      let errorType = this.isImage(fileName)[1]

      ///////////////////////////
      //替换avi后缀
      if(row.convertedMediaType === "mp4"){
        fileName = fileName.split(".")[0]+"."+row.convertedMediaType
      }

        //离线视频
      if (row.fileType === "1" || row.fileType === 1 || row.fileType === "video" || !imageFlag) {
        this.showSwitch.title = "视频浏览";
        this.showSwitch.show = false;//false是显示视频
        this.dialogVideoUrl = this.showSwitch.url + "/" + fileName
      }
      //图片
      else if (row.fileType === "2" || row.fileType === 2 || row.fileType === "image" || imageFlag) {
        this.showSwitch.show = true;//true是显示图片
        this.showSwitch.title = "图片浏览";
        this.dialogImageUrl = this.showSwitch.url + "/" + fileName;
      }
      let _this = this
      setTimeout(function (){
        _this.dialogVisible = true
      }, 1)
    },

    //记录选择的文件
    handleSelectionChange(val) {
      this.taskRequestData.taskFiles = []
      for(let i = 0; i<val.length;i++){
        let record = val[i]
        let id = record.id
        let data = {fileId: id, fileName:record.fileName, convertedMediaType:record.convertedMediaType}
        this.taskRequestData.taskFiles.push(data)
      }
      //////////////////////////////
      //在这里要对多边形点进行移除
      //////////////////////////////
    },

    ///////////////////////////////////
    //imageUrl为后台提供图片地址 画图
    /////////////////////////////////
    drawImageAndPoints(canvasId, imageOrVideoId, pointsOne, pointsTwo, flag=true, ifPointer=true, colorOne='red', colorTwo='green'){    //  获取canvas


      this.$nextTick(()=> {
        let canvas = document.getElementById(canvasId)    //由于弹窗，确保已获取到
        let imageOrVideo = document.getElementById(imageOrVideoId)
        // console.log(imageOrVideo)

        let _this = this
        setTimeout(function () {
          if (undefined !== canvas && canvas != null) {
            let a = setInterval(() => {
              canvas = document.getElementById(canvasId)
              let div = document.getElementsByClassName('collapseDiv')

              for (let i = 0; i < div.length; i++) {
                div[i].style.width = imageOrVideo.clientWidth + "px"
                div[i].style.height = imageOrVideo.clientHeight + "px"
              }
              _this.dialogStyle.width = imageOrVideo.clientWidth
              _this.dialogStyle.height = imageOrVideo.clientHeight
              if (!canvas) {
                return false
              } else {
                clearInterval(a)            //  可以理解为一个画笔，可画路径、矩形、文字、图像
                let context = canvas.getContext('2d')
                //  根据图像重新设定了canvas的长宽
                canvas.setAttribute("width",  _this.dialogStyle.width.toString())
                canvas.setAttribute("height", _this.dialogStyle.height.toString())           //  绘制图片

                // console.log("=================================")
                // console.log("imageOrVideo的大小："+_this.dialogStyle.width +"---"+ _this.dialogStyle.height)
                // console.log("imageOrVideo2的大小："+imageOrVideo.clientWidth +"---"+ imageOrVideo.clientHeight)

                // console.log(img.width+"-"+img.height)
                if (flag && pointsOne != null && pointsOne.length > 0) {
                  context.beginPath()
                  for (let i = 0; i < pointsOne.length; i++) {
                    let point1 = pointsOne[i]
                    let x1 = point1[0] * _this.dialogStyle.width
                    let y1 = point1[1] * _this.dialogStyle.height
                    let x2 = 0
                    let y2 = 0
                    if (i < pointsOne.length - 1) {
                      let point2 = pointsOne[i + 1]
                      x2 = point2[0] * _this.dialogStyle.width
                      y2 = point2[1] * _this.dialogStyle.height
                    } else {
                      let point2 = pointsOne[0]
                      x2 = point2[0] * _this.dialogStyle.width
                      y2 = point2[1] * _this.dialogStyle.height
                    }
                    context.moveTo(x1, y1)
                    context.lineTo(x2, y2)
                    context.strokeStyle = colorOne
                    context.lineWidth = 3;
                    context.stroke()
                  }
                }

                if (flag && pointsTwo != null && pointsTwo.length > 0) {
                  context.beginPath()
                  for (let i = 0; i < pointsTwo.length; i++) {
                    let point1 = pointsTwo[i]
                    let x1 = point1[0] * _this.dialogStyle.width
                    let y1 = point1[1] * _this.dialogStyle.height
                    let x2 = 0
                    let y2 = 0
                    if (i < pointsTwo.length - 1) {
                      let point2 = pointsTwo[i + 1]
                      x2 = point2[0] * _this.dialogStyle.width
                      y2 = point2[1] * _this.dialogStyle.height
                    } else {
                      let point2 = pointsTwo[0]
                      x2 = point2[0] * _this.dialogStyle.width
                      y2 = point2[1] * _this.dialogStyle.height
                    }
                    context.moveTo(x1, y1)
                    context.lineTo(x2, y2)
                    context.strokeStyle = colorTwo
                    context.lineWidth = 3;
                    context.stroke()
                  }
                }
                if(ifPointer){
                  canvas.style.pointerEvents = "auto"
                }else{
                  canvas.style.pointerEvents = "none"
                }
              }
            }, 50)
          }
        }, 130)
      })
    },


    taskFileShow(taskFiles, fileId, fileName){

      let fileNameTemp = fileName
      let index = 0
      for(index; index<taskFiles.length;index++){
        if(taskFiles[index].fileId === fileId){
          break
        }
      }

      let imageFlag = this.isImage(fileName)[0]
      let errorType = this.isImage(fileName)[1]

      ///////////////////////////
      //替换avi后缀
      if(undefined !== taskFiles[index].convertedMediaType && taskFiles[index].convertedMediaType === "mp4"){
        fileName = fileName.split(".")[0]+"."+ taskFiles[index].convertedMediaType
      }

      if(!errorType){
        if(imageFlag){
          this.showSwitch.isCreateTask = true
          this.dialogImageUrl = this.showSwitch.url +'/'+ fileName
          this.showSwitch.selectingFileName = fileNameTemp
          this.showSwitch.show = true
          this.showSwitch.title = "图片预览"
        }else {
          this.showSwitch.isCreateTask = true
          this.dialogVideoUrl = this.showSwitch.url +'/'+ fileName
          this.showSwitch.selectingFileName = fileNameTemp
          this.showSwitch.show = false
          this.showSwitch.title = "视频预览"
        }
        let _this = this
        setTimeout(function () {
          _this.dialogVisible = true
        }, 1)
      }else {
        this.$message.error("文件类型错误, 不支持该格式文件")
      }
    },


    drawPolygonEvent(fileName, isCheck){

      if(this.showSwitch.show){
        this.showSwitch.title = "图片预览"
      }else{
        this.showSwitch.title = "视频预览"
      }

      if(isCheck){
        this.showSwitch.title =  this.showSwitch.title + "（正在绘制待检测区域）"
        document.onmousedown = this.onmouseDown
      }else {
        //不检测区域
        this.showSwitch.title =  this.showSwitch.title + "（正在绘制非检测区域）"
        document.onmousedown = this.onmouseDownNoCheck
      }
      this.showSwitch.isDrawPolygon = true
      let _this = this
      setTimeout(function () {
        let imageFlag = _this.isImage(fileName)[0]
        let errorType = _this.isImage(fileName)[1]

        let canvas = null
        if(_this.showSwitch.show){
          canvas = document.getElementById('imageCanvas')
        }else{
          canvas = document.getElementById('videoCanvas')
        }
        if(canvas !== undefined && canvas != null){

          canvas.style.opacity = '0.7'
          // 一个任务中，一个文件一个多边形
          // this.polygonId = this.taskRequestData.taskFiles[index].fileId

          //一个任务一个多边形
          _this.polygonId = 0
          let index2 = 0
          if(_this.polygonPoint.length === 0){
            let p = {fileId: _this.polygonId, point:[]}
            _this.polygonPoint.push(p)
          }else{
            for(index2; index2 < _this.polygonPoint.length; index2++){
              if(_this.polygonPoint[index2].fileId ===  _this.polygonId){
                break
              }
            }
            if(index2 === _this.polygonPoint.length){
              let p = {fileId:_this.polygonId, point:[]}
              _this.polygonPoint.push(p)
            }
          }

          let index3 = 0
          if(_this.polygonNoCheckPoint.length === 0){
            let p = {fileId: _this.polygonId, point:[]}
            _this.polygonNoCheckPoint.push(p)
          }else{
            for(index3; index3 < _this.polygonNoCheckPoint.length; index3++){
              if(_this.polygonNoCheckPoint[index3].fileId ===  _this.polygonId){
                break
              }
            }
            if(index3 === _this.polygonNoCheckPoint.length){
              let p = {fileId:_this.polygonId, point:[]}
              _this.polygonNoCheckPoint.push(p)
            }
          }

          if(!errorType){
            if(imageFlag){
              if(_this.showSwitch.isDrawPolygon){
                _this.drawImageAndPoints('imageCanvas', "drawPolygonImage", _this.polygonPoint[index2].point, _this.polygonNoCheckPoint[index3].point)
              }
            }
            else{
              if(_this.showSwitch.isDrawPolygon){
                // let imageOrVideo = document.getElementById('drawPolygonVideo')
                // imageOrVideo.style.pointerEvents = "none"
                _this.drawImageAndPoints('videoCanvas', "drawPolygonVideo", _this.polygonPoint[index2].point, _this.polygonNoCheckPoint[index3].point)
              }
            }
          }else {
            _this.$message.error("文件类型错误, 不支持该格式文件")
          }
        }
      },30)

    }
  }
}

</script>

s
<style rel="stylesheet/scss" lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.image-preview {
  width: 178px;
  height: 178px;
  position: relative;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  float: left;
}

.image-preview .image-preview-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.image-preview .image-preview-wrapper img {
  width: 100%;
  height: 100%;
}

.image-preview .image-preview-action {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: default;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  background-color: rgba(0, 0, 0, .5);
  transition: opacity .3s;
  cursor: pointer;
  text-align: center;
  line-height: 200px;
}

.image-preview .image-preview-action .el-icon-delete {
  font-size: 32px;
}

.image-preview:hover .image-preview-action {
  opacity: 1;
}

.fileName::-webkit-scrollbar {
  width: 0 !important
}

#mycanvas {    border: 1px solid rgb(199, 198, 198);}

</style>




